package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.enums.CustomerDefaultAddressTypeEnum;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.CustomException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.customer.api.domain.CustomerAddressVo;
import com.probox.common.entity.domain.customer.CustomerAddress;
import com.probox.common.entity.domain.customer.CustomerInfo;
import com.probox.common.entity.mapper.customer.CustomerAddressMapper;
import com.probox.common.entity.mapper.customer.CustomerInfoMapper;
import com.probox.common.entity.service.common.SysReginService;
import com.probox.common.entity.service.customer.ICustomerAddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 客户收货地址Service业务层处理
 *
 * @author zsy
 * @date 2021-06-18
 */
@Service
@Transactional
public class CustomerAddressServiceImpl extends ServiceImpl<CustomerAddressMapper, CustomerAddress> implements ICustomerAddressService {
    @Autowired
    private CustomerAddressMapper customerAddressMapper;

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private SysReginService sysReginService;


    /**
     * 查询客户收货地址
     *
     * @param addressUid 客户收货地址ID
     * @return 客户收货地址
     */
    @Override
    public CustomerAddress selectCustomerAddressById(Long addressUid) {
        return this.getById(addressUid);
    }

    /**
     * 查询客户收货地址列表
     *
     * @param customerAddress 客户收货地址
     * @return 客户收货地址
     */
    @Override
    public List<CustomerAddress> queryList(CustomerAddress customerAddress) {
        QueryWrapper<CustomerAddress> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getAddressUid())) && customerAddress.getAddressUid() != null) {
            queryWrapper.eq("ADDRESS_UID", customerAddress.getAddressUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getCustomerUid())) && customerAddress.getCustomerUid() != null) {
            queryWrapper.eq("CUSTOMER_UID", customerAddress.getCustomerUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getName())) && customerAddress.getName() != null) {
            queryWrapper.eq("NAME", customerAddress.getName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getMobile())) && customerAddress.getMobile() != null) {
            queryWrapper.eq("MOBILE", customerAddress.getMobile());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getProvinceCode())) && customerAddress.getProvinceCode() != null) {
            queryWrapper.eq("PROVINCE_CODE", customerAddress.getProvinceCode());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getProvinceName())) && customerAddress.getProvinceName() != null) {
            queryWrapper.eq("PROVINCE_NAME", customerAddress.getProvinceName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getCityCode())) && customerAddress.getCityCode() != null) {
            queryWrapper.eq("CITY_CODE", customerAddress.getCityCode());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getCityName())) && customerAddress.getCityName() != null) {
            queryWrapper.eq("CITY_NAME", customerAddress.getCityName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getCountyCode())) && customerAddress.getCountyCode() != null) {
            queryWrapper.eq("COUNTY_CODE", customerAddress.getCountyCode());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getCountyName())) && customerAddress.getCountyName() != null) {
            queryWrapper.eq("COUNTY_NAME", customerAddress.getCountyName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getAddress())) && customerAddress.getAddress() != null) {
            queryWrapper.eq("ADDRESS", customerAddress.getAddress());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getPostCode())) && customerAddress.getPostCode() != null) {
            queryWrapper.eq("POST_CODE", customerAddress.getPostCode());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getIsDefault())) && customerAddress.getIsDefault() != null) {
            queryWrapper.eq("IS_DEFAULT", customerAddress.getIsDefault());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getUpdateUid())) && customerAddress.getUpdateUid() != null) {
            queryWrapper.eq("UPDATE_UID", customerAddress.getUpdateUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerAddress.getDataStatus())) && customerAddress.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", customerAddress.getDataStatus());
        }
        return customerAddressMapper.selectList(queryWrapper);
    }

    @Override
    public List<com.probox.common.entity.vo.customer.CustomerAddressVo> queryListvo(com.probox.common.entity.vo.customer.CustomerAddressVo customerAddress) {
        customerAddress.setPlatformUid(SecurityUtils.getPlatformId());
        Long[] region = customerAddress.getRegion();
        if (region != null){
            customerAddress.setProvinceCode(String.valueOf(region[0]));
            customerAddress.setCityCode(String.valueOf(region[1]));
            customerAddress.setCountyCode(String.valueOf(region[2]));
        }
        List<com.probox.common.entity.vo.customer.CustomerAddressVo> customerAddressVos = customerAddressMapper.queryCustomerAddress(customerAddress);
        return customerAddressVos;
    }

    /**
     * 新增客户收货地址(后台)
     *
     * @param customerAddress 客户收货地址
     * @return 结果
     */
    @Override
    public boolean insertCustomerAddress(CustomerAddress customerAddress) {
        //设置默认地址时,客户其他地址默认为否
        if (CustomerDefaultAddressTypeEnum.defaultAddress.getKey().equals(customerAddress.getIsDefault())){
            QueryWrapper<CustomerAddress> addressQueryWrapper = new QueryWrapper<>();
            addressQueryWrapper.eq("CUSTOMER_UID",customerAddress.getCustomerUid());
            addressQueryWrapper.eq("PLATFORM_UID",SecurityUtils.getPlatformId());
            addressQueryWrapper.eq("IS_DEFAULT",CustomerDefaultAddressTypeEnum.defaultAddress.getKey());
            List<CustomerAddress> customerAddresses = customerAddressMapper.selectList(addressQueryWrapper);
            for (CustomerAddress address:customerAddresses){
                address.setIsDefault(CustomerDefaultAddressTypeEnum.address.getKey());
                customerAddressMapper.updateById(address);
            }
        }
        customerAddress.setCustomerUid(customerAddress.getCustomerUid());
        customerAddress.setPlatformUid(SecurityUtils.getPlatformId());
        customerAddress.setDataStatus("1");
        customerAddress.setCreateTime(DateUtil.date());
        customerAddress.setCreateUid(SecurityUtils.getUserId());
        customerAddress.setCreateName(SecurityUtils.getUsername());
        return this.save(customerAddress);
    }

    /**
     * 新增客户收货地址(前端)
     *
     * @param customerAddress 客户收货地址
     * @return 结果
     */
    @Override
    public boolean insertCustomerAddressOpen(CustomerAddress customerAddress) {
        //设置默认地址时,客户其他地址默认为否
        if (CustomerDefaultAddressTypeEnum.defaultAddress.getKey().equals(customerAddress.getIsDefault())){
            QueryWrapper<CustomerAddress> addressQueryWrapper = new QueryWrapper<>();
            addressQueryWrapper.eq("CUSTOMER_UID",SecurityUtils.getCustomerUid());
            addressQueryWrapper.eq("PLATFORM_UID",SecurityUtils.getCustomerPlatformUid());
            addressQueryWrapper.eq("IS_DEFAULT",CustomerDefaultAddressTypeEnum.defaultAddress.getKey());
            List<CustomerAddress> customerAddresses = customerAddressMapper.selectList(addressQueryWrapper);
            for (CustomerAddress address:customerAddresses){
                address.setIsDefault(CustomerDefaultAddressTypeEnum.address.getKey());
                customerAddressMapper.updateById(address);
            }
        }
        customerAddress.setCustomerUid(SecurityUtils.getCustomerUid());
        customerAddress.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
        if (StringUtils.isEmpty(customerAddress.getCountyCode())) {
            String[] labels = new String[3];
            labels[0] = customerAddress.getProvinceName();
            labels[1] = customerAddress.getCityName();
            labels[2] = customerAddress.getCountyName();
            Long[] reginCode = sysReginService.getReginCode(labels);
            if (reginCode != null && reginCode.length == 3) {
                customerAddress.setProvinceCode(String.valueOf(reginCode[0]));
                customerAddress.setCityCode(String.valueOf(reginCode[1]));
                customerAddress.setCountyCode(String.valueOf(reginCode[2]));
            } else {
                throw new CustomException("省市区填写错误,请输入正确的省市区名称如：湖南省,长沙市,岳麓区");
            }
        }
        customerAddress.setDataStatus("1");
        customerAddress.setCreateTime(DateUtil.date());
        customerAddress.setCreateUid(SecurityUtils.getCustomerUid());
        customerAddress.setCreateName(SecurityUtils.getCustomerUserName());
        return this.save(customerAddress);
    }

    /**
     * 修改客户收货地址(后台)
     *
     * @param customerAddress 客户收货地址
     * @return 结果
     */
    @Override
    public boolean updateCustomerAddress(CustomerAddress customerAddress) {
        //设置默认地址时,客户其他地址默认为否
        if (CustomerDefaultAddressTypeEnum.defaultAddress.getKey().equals(customerAddress.getIsDefault())){
            QueryWrapper<CustomerAddress> addressQueryWrapper = new QueryWrapper<>();
            addressQueryWrapper.eq("CUSTOMER_UID",customerAddress.getCustomerUid());
//            addressQueryWrapper.eq("PLATFORM_UID",SecurityUtils.getPlatformId());
            addressQueryWrapper.eq("IS_DEFAULT",CustomerDefaultAddressTypeEnum.defaultAddress.getKey());
            List<CustomerAddress> customerAddresses = customerAddressMapper.selectList(addressQueryWrapper);
            for (CustomerAddress address:customerAddresses){
                address.setIsDefault(CustomerDefaultAddressTypeEnum.address.getKey());
                customerAddressMapper.updateById(address);
            }
        }

        String[] labels = new String[3];
        labels[0] = customerAddress.getProvinceName();
        labels[1] = customerAddress.getCityName();
        labels[2] = customerAddress.getCountyName();
        Long[] reginCode = sysReginService.getReginCode(labels);
        if (reginCode != null && reginCode.length == 3){
            customerAddress.setProvinceCode(String.valueOf(reginCode[0]));
            customerAddress.setCityCode(String.valueOf(reginCode[1]));
            customerAddress.setCountyCode(String.valueOf(reginCode[2]));
        }else {
            throw new CustomException("省市区填写错误,请输入正确的省市区名称如：湖南省,长沙市,岳麓区");
        }
        customerAddress.setUpdateUid(SecurityUtils.getUserId());
        customerAddress.setUpdateTime(DateUtil.date());
        customerAddress.setUpdateName(SecurityUtils.getUsername());
        return this.updateById(customerAddress);
    }

    /**
     * 修改客户收货地址(前端)
     *
     * @param customerAddress 客户收货地址
     * @return 结果
     */
    @Override
    public boolean updateCustomerAddressOpen(CustomerAddress customerAddress) {
        //设置默认地址时,客户其他地址默认为否
        if (CustomerDefaultAddressTypeEnum.defaultAddress.getKey().equals(customerAddress.getIsDefault())){
            QueryWrapper<CustomerAddress> addressQueryWrapper = new QueryWrapper<>();
            addressQueryWrapper.eq("CUSTOMER_UID",SecurityUtils.getCustomerUid());
            addressQueryWrapper.eq("PLATFORM_UID",SecurityUtils.getCustomerPlatformUid());
            addressQueryWrapper.eq("IS_DEFAULT",CustomerDefaultAddressTypeEnum.defaultAddress.getKey());
            List<CustomerAddress> customerAddresses = customerAddressMapper.selectList(addressQueryWrapper);
            for (CustomerAddress address:customerAddresses){
                address.setIsDefault(CustomerDefaultAddressTypeEnum.address.getKey());
                customerAddressMapper.updateById(address);
            }
        }
        if (StringUtils.isEmpty(customerAddress.getCountyCode())) {
            String[] labels = new String[3];
            labels[0] = customerAddress.getProvinceName();
            labels[1] = customerAddress.getCityName();
            labels[2] = customerAddress.getCountyName();
            Long[] reginCode = sysReginService.getReginCode(labels);
            if (reginCode != null && reginCode.length == 3) {
                customerAddress.setProvinceCode(String.valueOf(reginCode[0]));
                customerAddress.setCityCode(String.valueOf(reginCode[1]));
                customerAddress.setCountyCode(String.valueOf(reginCode[2]));
            } else {
                throw new CustomException("省市区填写错误,请输入正确的省市区名称如：湖南省,长沙市,岳麓区");
            }
        }
        customerAddress.setUpdateUid(SecurityUtils.getCustomerUid());
        customerAddress.setUpdateTime(DateUtil.date());
        customerAddress.setUpdateName(SecurityUtils.getCustomerUserName());
        return this.updateById(customerAddress);
    }

    /**
     * 批量删除客户收货地址
     *
     * @param addressUids 需要删除的客户收货地址ID
     * @return 结果
     */
    @Override
    public boolean deleteCustomerAddressByIds(Long[] addressUids) {
        return this.removeByIds(Arrays.asList(addressUids));
    }

    /**
     * 根据地址id返回地址信息
     * @param addressId
     * @return
     */
    @Override
    public CustomerAddressVo getCustomerAddressInfo(Long addressId) {
        CustomerAddressVo customerAddressVo = customerAddressMapper.selectCustoemrAddressById(addressId);
        return customerAddressVo;
    }

    /**
     * 获取当前客户默认地址
     * @return
     */
    @Override
    public CustomerAddress getDefaultAddress(Long customerId) {
        if (customerId == null){
            customerId = SecurityUtils.getCustomerUid();
        }
        QueryWrapper<CustomerAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_UID", customerId);
        queryWrapper.eq("DATA_STATUS", "1");
        queryWrapper.eq("IS_DEFAULT", "1");
        CustomerAddress customerAddress = customerAddressMapper.selectOne(queryWrapper);
        return customerAddress;
    }

    @Override
    public Boolean updateAddressStatus(CustomerAddress customerAddress) {
        CustomerAddress address = customerAddressMapper.selectById(customerAddress);
        address.setUpdateUid(SecurityUtils.getUserId());
        address.setUpdateName(SecurityUtils.getUsername());
        address.setUpdateTime(DateUtil.date());
        address.setDataStatus(customerAddress.getDataStatus());
        return this.updateById(address);
    }

    /**
     * 查询客户地址详细
     * @param addressUid
     * @return
     */
    @Override
    public AjaxResult selectCustomerAddressDetail(Long addressUid) {
        AjaxResult ajax = AjaxResult.success();
        CustomerAddress customerAddress = this.getById(addressUid);
        com.probox.common.entity.vo.customer.CustomerAddressVo customerAddressVo = new com.probox.common.entity.vo.customer.CustomerAddressVo();
        BeanUtils.copyProperties(customerAddress, customerAddressVo);
        Long[] region = new Long[3];
        if (customerAddress.getProvinceCode()!=null && customerAddress.getCityCode()!=null && customerAddress.getCountyCode()!=null){
            region[0] = Long.parseLong(customerAddress.getProvinceCode());
            region[1] = Long.parseLong(customerAddress.getCityCode());
            region[2] = Long.parseLong(customerAddress.getCountyCode());
        }
        customerAddressVo.setRegion(region);
        CustomerInfo customerInfo = customerInfoMapper.selectById(customerAddress.getCustomerUid());
        customerAddressVo.setCustomerName(customerInfo.getCustomerName());
        ajax.put("customerAddress", customerAddressVo);
        return ajax;
    }

    /**
     * 查询当前客户所有地址
     * @return
     */
    @Override
    public List<CustomerAddress> getCustomerAllAddress() {
        QueryWrapper<CustomerAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_UID",SecurityUtils.getCustomerUid());
//        queryWrapper.eq("PLATFORM_UID",SecurityUtils.getCustomerPlatformUid());
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        List<CustomerAddress> customerAddresses = customerAddressMapper.selectList(queryWrapper);
        return customerAddresses;
    }

    @Override
    public Integer getCustomerAllAddressCount() {
        QueryWrapper<CustomerAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_UID",SecurityUtils.getCustomerUid());
//        queryWrapper.eq("PLATFORM_UID",SecurityUtils.getCustomerPlatformUid());
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        Integer customerAddressesCount = customerAddressMapper.selectCount(queryWrapper);
        return customerAddressesCount;
    }

    @Override
    public List<com.probox.common.entity.vo.customer.CustomerAddressVo> getByIdAddress(Long customerUid) {
        List<com.probox.common.entity.vo.customer.CustomerAddressVo> customerAddressVoList = customerAddressMapper.queryCustomerAddressByid(customerUid);
        return customerAddressVoList;
    }


}
